package com.olympia.myapp.activity;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.olympia.myapp.R;
import com.olympia.myapp.base.BaseActivity;
import com.olympia.myapp.custom.Dialog_Confirm;
import com.olympia.myapp.custom.Dialog_Confirm.ProcessDialogConfirm;
import com.olympia.myapp.entity.QuestionKD;
import com.olympia.myapp.server.HttpConnection;
import com.olympia.myapp.util.AnimationControl;
import com.olympia.myapp.util.Constants;
import com.olympia.myapp.util.ControlListener;
import com.olympia.myapp.util.Reminder;
import com.olympia.myapp.util.WaitingReminder;
import com.olympia.myapp.xml.QuestionXMLHandler;

public class StartActivity extends BaseActivity {
	ProgressBar progress = null;
	int typeConnect = 0;// 0
	Dialog_Confirm dgConfirm = null;
	TextView txtScore;
	TextView txtNumAnswer;
	TextView txtQuestionContent;
	TextView txtQuestionAnswer;
	TextView txtName;
	TextView txtQuestionNumber;

	Button btnA;
	Button btnB;
	Button btnCancel;

	int size = 12;
	int numTotal = 0;
	int numCorrect = 0;
	boolean isAnswer = true;
	List<QuestionKD> arrQSKD = null;
	AnimationControl animateControl = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.startactivity);
		intent = getIntent();

		animateControl = new AnimationControl();
		numTotal = numCorrect = 0;
		Constants.SCORE = 0;
		progress = (ProgressBar) findViewById(R.id.progress);
		showhideProgress(false);

		txtScore = (TextView) findViewById(R.id.start_layout_right_score);
		txtNumAnswer = (TextView) findViewById(R.id.start_layout_right_numanswer);

		btnA = (Button) findViewById(R.id.start_layout_bottom_btnA);
		btnA.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				checkAnswer("a");
			}
		});
		btnB = (Button) findViewById(R.id.start_layout_bottom_btnB);
		btnB.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				checkAnswer("b");
			}
		});
		btnCancel = (Button) findViewById(R.id.start_layout_bottom_btnCancel);
		btnCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				checkAnswer("-1");
			}
		});

		txtQuestionContent = (TextView) findViewById(R.id.start_layout_question_content);
		txtQuestionAnswer = (TextView) findViewById(R.id.start_layout_question_answer);
		txtName = (TextView) findViewById(R.id.start_layout_caption_name);
		txtQuestionNumber = (TextView) findViewById(R.id.start_layout_caption_totalNum);

		Constants.myService.playKD();
		// hien thi dialog truoc khi choi
		showDialogConfirm(0, getString(R.string.note_title),
				getString(R.string.alert2));

		if (QuestionXMLHandler.qsKD != null
				&& QuestionXMLHandler.qsKD.size() > 0)
			arrQSKD = QuestionXMLHandler.qsKD;

		showLayoutQS(false);
		size = arrQSKD.size();
		txtName.setText(Constants.myAccount.name);
		txtQuestionNumber.setText(String.valueOf(size) + " câu hỏi");
		updateValue();
		loadQuestion(numTotal);
	}

	QuestionKD question = null;

	private void loadQuestion(int num) {
		showLayoutQS(true);
		if (num < size) {
			question = arrQSKD.get(num);
			if (question != null) {
				txtQuestionContent.setText(question.content);
				animateControl.RunAnimations(this, txtQuestionContent,
						R.anim.alpha);
				txtQuestionAnswer.setText(question.answerContent);
				animateControl.RunAnimations(this, txtQuestionAnswer,
						R.anim.alpha);

				animateControl.RunAnimations(this, btnA, R.anim.alpha);
				animateControl.RunAnimations(this, btnB, R.anim.alpha);
				animateControl.RunAnimations(this, btnCancel, R.anim.alpha);
			}
		}
	}

	private void updateValue() {
		txtScore.setText(String.valueOf(Constants.SCORE));
		txtNumAnswer.setText(String.valueOf(numCorrect) + "/" + numTotal);
	}

	/**
	 * ẩn hiện progressbar
	 * 
	 * @param isShow
	 */
	private void showhideProgress(boolean isShow) {
		isRequest = isShow;
		progress.setVisibility(isShow ? View.VISIBLE : View.GONE);
	}

	/*
	 * hien thi dialog confirm
	 */
	private void showDialogConfirm(final int type, String title, String content) {
		if (!isFinishing()) {
			dgConfirm = new Dialog_Confirm(StartActivity.this, title, content,
					type != 2 ? false : true, true, new ProcessDialogConfirm() {
						public void click_Ok() {
							// truong hop bi loi ket noi
							acceptScore();
							dgConfirm.dismiss();
						}

						public void click_Cancel() {
							dgConfirm.dismiss();
							if (type == 0) {
								// tắt âm thanh và bắt đầu chơi
								Constants.myService.pauseKD();

								changeTime();

							} else if (type == 1) {
								// gui xác nhận số điểm đã chơi
								acceptScore();
							} else if (type == 2) {
								finish();
							}
						}
					});

			dgConfirm.setContent(content);
			dgConfirm.setCancelable(false);
			dgConfirm.show();

			if (type == 0 || type == 1)
				dgConfirm.setTextOnButton("", "Tiếp tục");
		}
	}

	String urlScore = "";

	private void acceptScore() {
		typeConnect = 0;
		urlScore = urlUtil.acceptScore(Constants.myAccount.mail,
				String.valueOf(Constants.SCORE));
		requestServer(urlScore);
	}

	// ====================== Gui yeu cau len server ========================
	public void requestServer(String url) {
		if (!isRequest) {
			Handler handler = new Handler() {
				@Override
				public void handleMessage(Message message) {
					switch (message.what) {
					case HttpConnection.DID_START: {
						showhideProgress(true);
						break;
					}
					case HttpConnection.DID_SUCCEED: {
						String result = message.obj.toString();
						try {
							processDataResult(result, message.arg1);
						} catch (IOException e) {
							e.printStackTrace();
						}
						showhideProgress(false);
						break;
					}
					case HttpConnection.DID_ERROR: {
						showhideProgress(false);
						showDialogConfirm(2, getString(R.string.note_title),
								getString(R.string.error_connect));
						break;
					}
					}
				}
			};

			new HttpConnection(handler).get(url, typeConnect);
		}
	}

	private void processDataResult(String str, int index) throws IOException {
		if (str != null && str.length() > 0) {
			switch (index) {
			case 0:// xác nhận điểm đã chơi
					// chuyển sang màn thi VCNV
				if (str.contains("<result>OK</result>")) {
					intent = new Intent(StartActivity.this, VCNVActivity.class);
					startActivity(intent);
					overridePendingTransition(R.anim.fase_in, R.anim.fade_out);
					finish();
				}
				break;
			case 1:
				break;
			default:
				break;
			}
		}
	}

	/**
	 * kiem tra cau tra loi
	 * 
	 * @param rs
	 */
	private void checkAnswer(String rs) {
		if (isAnswer) {
			if (rs.toUpperCase().compareTo(question.answer.toUpperCase()) == 0) {
				// tra loi dung
				numCorrect++;
				// phat am thanh đúng
				if (!isFinishing()) {
					int ran = (new Random()).nextInt(100) % 2;
					if (ran == 0)
						Constants.myService.playCorrect1();
					else
						Constants.myService.playCorrect2();
					// cong diem
					Constants.SCORE += 10;
				}
			} else {
				// phát âm thanh sai
				if (!isFinishing())
					Constants.myService.playUnCorrect2();
			}

			if (numTotal == size - 1) {
				isAnswer = false;
				// tăng số câu trả lời
				numTotal++;
				// cập nhật điểm số
				updateValue();
				// hien thi dialog hoan thanh
				String str = String.format(
						getResources().getString(R.string.start_content_score),
						"KHỞI ĐỘNG", Constants.SCORE);
				showDialogConfirm(1, getString(R.string.note_title), str);
			} else {
				// tăng số câu trả lời
				numTotal++;
				// cập nhật điểm số
				updateValue();
				// ẩn ko cho chọn tiếp
				showLayoutQS(false);
				// chờ 2s
				waitingRemind.start(1200);
			}
		}
	}

	/**
	 * ẩn hiện nội dung và nút bấm
	 */
	private void showLayoutQS(boolean isShow) {
		if (isShow) {
			((RelativeLayout) findViewById(R.id.start_layout_bottom))
					.setVisibility(View.VISIBLE);
		} else {
			txtQuestionContent.setText("");
			txtQuestionAnswer.setText("");
			((RelativeLayout) findViewById(R.id.start_layout_bottom))
					.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * thay đổi vị trí theo đồng hôg thời gian
	 */
	private Reminder remind = null;
	ImageView imgRec = null;
	RelativeLayout layBar2 = null;
	int time = 62;
	int left = 0;
	int right = 0;
	int top = 0;
	int bottom = 0;
	float percel = 5;
	ControlListener controlZoom = new ControlListener() {
		public void runTask() {
			if (!isFinishing())
				Constants.myService.playClick();
			top += percel;
			layBar2.setPadding(0, top, 0, 0);
		}

		public void stopTask() {
			if (isAnswer) {
				// hien thi dialog hoan thanh
				String str = String.format(
						getResources().getString(R.string.start_content_score),
						"KHỞI ĐỘNG", Constants.SCORE);
				showDialogConfirm(1, getString(R.string.note_title), str);
			}
			isAnswer = false;
		}
	};

	private void changeTime() {
		layBar2 = (RelativeLayout) findViewById(R.id.start_layout_right_bar2);

		Bitmap bm = BitmapFactory.decodeResource(getResources(),
				R.drawable.ic_rec);
		left = 0;
		right = bm.getWidth();
		top = 0;
		bottom = bm.getHeight();
		int bar2H = layBar2.getHeight() + bottom;
		percel = (float) (bar2H / 59);

		imgRec = new ImageView(this);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				right, bottom);
		imgRec.setBackgroundResource(R.drawable.ic_rec);
		imgRec.setEnabled(false);

		layBar2.addView(imgRec, layoutParams);

		this.remind = new Reminder(controlZoom, time);
		this.remind.start(1);
	}

	/*
	 * dung 5s trước khi load câu hỏi tiếp theo
	 */
	WaitingReminder waitingRemind = new WaitingReminder(new ControlListener() {
		public void runTask() {
			// stop âm thanh

			// load câu hỏi tiếp theo
			loadQuestion(numTotal);
		}
	});

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		Constants.myService.clearAll();
		super.onBackPressed();
	}
}
